﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace T4UtilityBelt.UxDesigns.Bindings
{
    public class BindingCollection : Collection<Binding>
    {
        public BindingCollection()
        {
            _bindingsByTargetName = new Dictionary<string, Binding>();
        }

        private readonly Dictionary<string, Binding> _bindingsByTargetName;

        public Binding this[string index]
        {
            get
            {
                return _bindingsByTargetName[index];
            }
        }

        protected override void ClearItems()
        {
            base.ClearItems();
            _bindingsByTargetName.Clear();
        }

        protected override void RemoveItem(int index)
        {
            Binding item = this[index];
            if (_bindingsByTargetName.ContainsKey(item.TargetName))
            {
                _bindingsByTargetName.Remove(item.TargetName);
            }
            base.RemoveItem(index);
        }

        protected override void InsertItem(int index, Binding item)
        {
            if (_bindingsByTargetName.ContainsKey(item.TargetName))
            {
                throw new BindingException("Binding already exists for target: " + item.TargetName);
            }
            _bindingsByTargetName.Add(item.TargetName, item);
            base.InsertItem(index, item);
        }

        protected override void SetItem(int index, Binding item)
        {
            _bindingsByTargetName[item.TargetName] =  item;
            base.SetItem(index, item);
        }
    }
}
